package com.moon;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.sys.DemoApp;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.widget.CircleImageView;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class PersonInfoActivity extends BaseActivity implements OnClickListener{
	JSONObject mMember = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_person_info);
		((TextView) findViewById(R.id.center)).setText("详细信息");
		((TextView) findViewById(R.id.name)).setText(getIntent().getStringExtra("name"));

		if(getIntent().getStringExtra("userId").equals(PreferencesUtils.getString(this, "userId")))
		{
			findViewById(R.id.bak_layout).setVisibility(View.GONE);
		}
		else
		{
			((Button) findViewById(R.id.right)).setText("修改");
		}
		
		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.right).setOnClickListener(this);
		findViewById(R.id.btn0).setOnClickListener(this);
		findViewById(R.id.btn1).setOnClickListener(this);
		findViewById(R.id.btn2).setOnClickListener(this);
		findViewById(R.id.img_show).setOnClickListener(this);
		findViewById(R.id.del).setOnClickListener(this);
		
		if(getIntent().getExtras().getInt("flag") == 1)
		{
			findViewById(R.id.btn2).setVisibility(View.GONE);
		}
		
		if(getIntent().getStringExtra("userId").equals(PreferencesUtils.getString(this, "userId")))
		{
			findViewById(R.id.layout).setVisibility(View.INVISIBLE);
		}
		
		findViewById(R.id.scrollview).setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				EditText edit=(EditText)findViewById(R.id.text0);  
		        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		        imm.hideSoftInputFromWindow(edit.getWindowToken(),0);			
		        
		        return v.onTouchEvent(event);
			}
		});
		
		sendHttpRequest();
	}

	@Override
	public void onClick(View arg0) {
		EditText edit=(EditText)findViewById(R.id.text0);  
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(edit.getWindowToken(),0);	
		
		int viewId = arg0.getId();
		switch(viewId)
		{
		case R.id.left:
			finish();
			break;
			
		case R.id.btn2:
			RongIM.getInstance().startPrivateChat(this,
					getIntent().getStringExtra("userId"), 
					getIntent().getStringExtra("name"));
			break;
		
		case R.id.btn0:
		{
			if(mMember == null) return;
			try
			{
				Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+ mMember.getString("telephone")));  
				startActivity(intent);  
			}
			catch(Exception e)
			{
				ToastUtil.showToastWithAlertPic("您还没有授权");
			}
			break;
		}
		
		case R.id.btn1:
		{
			if(mMember == null) return;
			try
			{
				Intent sendIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("smsto:" + mMember.getString("telephone")));
				startActivity(sendIntent);
			}
			catch(Exception e)
			{
				ToastUtil.showToastWithAlertPic("您还没有授权");
			}
			break;
		}
		
		case R.id.img_show:
		{
			Intent intent = new Intent(this,UserDisActivity.class);
			intent.putExtra("userId", getIntent().getStringExtra("userId"));
			startActivity(intent);
		}
			break;
		
		case R.id.right:
			sendRequest();
			break;
		}
	}
	
	private void sendHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("statusCode").equals("0")) {
					mMember = ruser.getJSONObject("member");
					
					((TextView)findViewById(R.id.name)).setText(mMember.getString("username"));

					String bak = mMember.getString("alias");
					if(bak != null) ((EditText)findViewById(R.id.text0)).setText(bak);

					String path = mMember.getString("avatar_path");
					if(path != null && path.length() != 0) path = "http://120.27.129.233/ylbb/" + path;
					else path = "";
					if(mMember.getInteger("is_teacher") == 0)
						ImageLoaderHelper.displayImage(R.drawable.ic_family, (CircleImageView)findViewById(R.id.icon),path);
					else 
						ImageLoaderHelper.displayImage(R.drawable.ic_teacher, (CircleImageView)findViewById(R.id.icon),path);
					
					setUserInfo();
					
					JSONObject lastestnews = mMember.getJSONObject("lastestnews");
					if(lastestnews != null)
					{
						String str = lastestnews.getString("attach");
						String array[] = str.split(",");
						
						for(int i = 0; i < array.length; i++)
						{
							findViewById(R.id.img0 + i).setVisibility(View.VISIBLE);
							ImageLoaderHelper.displayImage(R.drawable.icon_album, (ImageView)findViewById(R.id.img0 + i),
									"http://120.27.129.233/ylbb/api/get_attach?id=" + array[i] + "&width=160&height=160");
						}
					}
				}
				else
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};

		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(this, "userId"));
		params.put("member_id", getIntent().getStringExtra("userId"));
		MgqRestClient.get("get_member_info", params, loginHandler);
	}
	
	private void setUserInfo() {
		JSONArray child = mMember.getJSONArray("child");
		JSONArray classes = new JSONArray(mMember.getJSONArray("classes"));
		StringBuffer buffer = new StringBuffer();
		
		int count = classes.size();
		for(int i = 0; i < count; i++)
		{
			JSONObject classItem = classes.getJSONObject(i);

			if(buffer.length() > 0) buffer.append("\n");
			buffer.append(classItem.getString("school_name"));
			if(classItem.getString("class_alias") != null) buffer.append(classItem.getString("class_alias"));
			else buffer.append(classItem.getString("class_name"));
			buffer.append("\n");
			if(classItem.getInteger("is_teacher") > 0) buffer.append(classItem.getString("identitylabel"));
			
			if(child != null)
			{
				int len = child.size();
				boolean isAdd = false;
				for(int j = 0; j < len; j++)
				{
					JSONObject item = child.getJSONObject(j);
					if(item.getInteger("class_id") == classItem.getInteger("id"))
					{
						if(classItem.getInteger("is_teacher") > 0 || isAdd) buffer.append(",");
						buffer.append(item.getString("name"));
						if(item.getString("identity") != null) buffer.append(item.getString("identity"));
						isAdd = true;
					}
				}
			}
		}

		((TextView)findViewById(R.id.content)).setText(buffer.toString());
	}
	
	private void sendRequest() {
		final String nick = ((EditText)findViewById(R.id.text0)).getText().toString();
		MgqDataHandler loginHandler = new MgqDataHandler(this, false, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
					ToastUtil.showToastWithAlertPic("修改成功");
					sendMemberRequest();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(this, "userId"));
		params.put("member_id", getIntent().getStringExtra("userId"));
		params.put("alias", nick);
		MgqRestClient.get("set_member_alias", params, loginHandler);
	}
	
	public void sendMemberRequest() {
		final String nick = ((EditText)findViewById(R.id.text0)).getText().toString();
		JSONObject item = ((DemoApp)getApplicationContext()).mMembers
				.getJSONObject(getIntent().getStringExtra("userId"));
		item.put("alias", nick);
		
		String name = item.getString("alias");
		if(name == null || name.length() == 0) name = item.getString("username");
		
		String path = "";
		try
		{
			path = item.getString("avatar");
		}catch(Exception e){}
		if(path == null || path.length() == 0)
		{
			if(item.getInteger("is_teacher") == 1) path = "http://odv1e0gp0.bkt.clouddn.com/ic_teacher.png";
			else path = "http://odv1e0gp0.bkt.clouddn.com/ic_family.png";
		}
		else path = "http://120.27.129.233/ylbb/" + path;
		RongIM.getInstance().refreshUserInfoCache(new UserInfo(getIntent().getStringExtra("userId"),
				name,Uri.parse(path)));
	}
}
